<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2017-12-22
 * Time: 下午 10:30
 */
error_reporting(E_ALL ^ E_NOTICE);
require_once 'JKSocket.php';
$inputHandle = fopen('php://stdin', 'r');;
stream_set_blocking($inputHandle, 0);
// stream_set_timeout($inputHandle, 0, 20);
$strBuffer = '';

$client = new JKSocket(8800);

$client->onConnect(function (JKSocket $obj, $args) {
    echo "Connect server {$obj->getAddr()} success\n";
});

$client->onClose(function (JKSocket $obj, $args) {
   echo "Connect close\n"; 
});

$client->onRecv(function (JKSocket $obj, $args) {
    $data = $args['data'];
    $jsonData = json_decode($data, true);
    
    if(null === $jsonData) {
        echo "Error format recv\n";
        return;
    }
    
    if($jsonData['type'] == 'message') {
        echo "Client #{$jsonData['client']} {$jsonData['date']}: {$jsonData['message']}\n";
        return;
    }
    
    if($jsonData['type'] == 'entry_room') {
        echo "Entry Room {$jsonData['room']}, id: {$jsonData['index']}\n";
        return;
    }
    
});

$client->onRecvStep(function(JKSocket $client) use ($inputHandle, &$strBuffer) {
    $inputs = [STDIN];
    
    if(stream_select($inputs, $write, $except, 0) < 1) {
        return;
    }
    
    var_dump('sdsd');
    
    $buffer = trim(stream_get_line($inputHandle, 1));
    
    // if(false === strpos("\n", $buffer)) {
    //     $strBuffer .= $buffer;
    //     return;
    // }
    //
    // $lines = explode("\n", $buffer);
    // $firstLine = array_shift($lines);
    // $strBuffer .= $firstLine;
    // $strBuffer = trim($strBuffer);
    
    if('' !== $buffer) {
        $client->send(json_encode(['type' => 'message', 'message' => $buffer]));
    }
    
    // foreach ($lines as $line) {
    //     $line = trim($line);
    //     if('' !== $line) {
    //         $client->send(json_encode(['type' => 'message', 'message' => $line]));
    //     }
    // }
});

if($client->connect()->fail()) {
    echo $client->getLastError();
}